package leetcode.editor.test;


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyClass {
    public static void main(String[] args) {
        //普通执行方式
        Person girl = new Girl();
//        girl.say();
        //通过代理类执行
        Person person = new ProxyPerson(girl).getPerson();
        person.say();
    }
}

/**
 * 动态代理类
 */
class ProxyPerson implements InvocationHandler{
    Person person;

    public ProxyPerson(Person person) {
        this.person = person;
    }

    //得到代理类对象
    public Person getPerson() {
        Object proxyInstance = Proxy.newProxyInstance(person.getClass().getClassLoader(),
                person.getClass().getInterfaces(), this);
        return ((Person) proxyInstance);
    }

    /**
     * 动态代理Invoke方法
     * @param proxy
     * @param method
     * @param args
     * @return
     * @throws Throwable
     */
    @Override
    public Person invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //被代理方法执行之前
        System.out.println("代理方法执行之前");
        Person person = (Person) method.invoke(this.person, args);
        System.out.println("代理方法执行之后");
        return person;
    }
}
class Girl implements Person{

    @Override
    public void say() {
        System.out.println("我是一个女孩");
    }
}
class Boy implements Person {
    @Override
    public void say() {
        System.out.println("我是一个男孩!!");
    }
}
interface Person{
     void say();
}
